﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WenPostTool.Controls;
using System.Data.SQLite;

namespace WenPostTool
{
    public partial class Form1 : WenSkin.Forms.WenForm
    {
        string dbpath = $"{Application.StartupPath}\\Data\\data.db";
        public Form1()
        {
            InitializeComponent();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            CreateDb();
            ReData();
        }

        private void postUserControl1_PostClick(object sender, Controls.PostUserControl.PostClickEventArgs e)
        {
            AddData(e.HistoryItem);
        }

        private void AddData(HistoryItem item)
        {
            historyControl1.Items.Add(item);

            string txtpath = $"{Application.StartupPath}\\Data\\Info\\{DateTime.Now:yyyyddMM_HHmmssffff}.txt";
            //保存内容到制定文件
            StreamWriter sw = new StreamWriter(txtpath, true, Encoding.UTF8);
            sw.Write(item.ResultInfo);
            sw.Flush();
            sw.Close();

            string sql = $"insert into History (Post,Url,Text,ResultInfo,DateTime) values " +
                $"('{item.Post}','{item.Url}','{item.Text.Replace("'","''")}','{item.ResultInfo.Replace("'", "''")}','{item.DateTime}') " +
                $";select last_insert_rowid();";
            SQLiteConnection cn = new SQLiteConnection("data source=" + dbpath);
            if (cn.State != System.Data.ConnectionState.Open)
            {
                cn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = cn;
                cmd.CommandText = sql;
                item.Id = Convert.ToInt32(cmd.ExecuteScalar());
            }
            cn.Close();
        }

        private void CreateDb()
        {
            if (File.Exists(dbpath))
                return;
            Directory.CreateDirectory($"{Application.StartupPath}\\Data");
            Directory.CreateDirectory($"{Application.StartupPath}\\Data\\Info");
            SQLiteConnection.CreateFile(dbpath);
            SQLiteConnection cn = new SQLiteConnection("data source=" + dbpath);
            if (cn.State != System.Data.ConnectionState.Open)
            {
                cn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = cn;
                cmd.CommandText = "CREATE TABLE History(";
                cmd.CommandText += "ID INTEGER PRIMARY KEY,";
                cmd.CommandText += "Post nvarchar(50),";
                cmd.CommandText += "Url nvarchar(500),";
                cmd.CommandText += "Text Text,";
                cmd.CommandText += "ResultInfo Text,";
                cmd.CommandText += "DateTime nvarchar(50)";
                cmd.CommandText += ")";
                cmd.ExecuteNonQuery();
            }
            cn.Close();
        }

        private void ReData()
        {
            string sql = "select * from History order by id limit 100 offset 0";

            SQLiteConnection cn = new SQLiteConnection("data source=" + dbpath);
            if (cn.State != System.Data.ConnectionState.Open)
            {
                cn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = cn;
                cmd.CommandText = sql;

                SQLiteDataReader sr = cmd.ExecuteReader();

                DataTable dt = new DataTable();
                dt.Load(sr);

                historyControl1.Items.Clear();
                foreach (DataRow dr in dt.Rows)
                {
                    HistoryItem item = new HistoryItem()
                    {
                        Id = int.Parse(dr["id"]?.ToString()),
                        Post = dr["POST"]?.ToString(),
                        Text = dr["TEXT"]?.ToString(),
                        Url = dr["Url"]?.ToString(),
                        ResultInfo = dr["ResultInfo"]?.ToString(),
                        DateTime = DateTime.Parse(dr["DateTime"]?.ToString()),
                    };
                    historyControl1.Items.Add(item);
                }
            }
            cn.Close();
        }

        private void historyControl1_DeleteClick(object sender, HistoryControl.PostClickEventArgs e)
        {
            string sql = $"delete from History where id='{e.HistoryItem.Id}'";
            SQLiteConnection cn = new SQLiteConnection("data source=" + dbpath);
            if (cn.State != System.Data.ConnectionState.Open)
            {
                cn.Open();
                SQLiteCommand cmd = new SQLiteCommand();
                cmd.Connection = cn;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
            }
            cn.Close();
        }

        private void historyControl1_ItemClick(object sender, HistoryControl.PostClickEventArgs e)
        {
            postUserControl1.InsertHistoryData(e.HistoryItem);
        }
    }
}
